package com.omg.server.util;

import java.io.IOException;

import net.htmlparser.jericho.Source;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;
import org.apache.log4j.Logger;



public class HttpSenderUtil {
	private static Logger logger = Logger.getLogger(HttpSenderUtil.class);
	
	//获取商口品的目标地址
	public static String getTargetUrl(String url){
		String result = "";
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		// 创建GET方法的实例
		PostMethod getMethod = new PostMethod(url);
		getMethod.setRequestHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; InfoPath.2; staticlogin:product=cboxf2010&act=login&info=ZmlsZW5hbWU9UG93ZXJXb3JkMjAxME94Zl9VbHRpbWF0ZS5leGUmbWFjPTU2ODE4RkIyMDYyNzQyNkY4RTExRkU5OUVDNEE5RDM3JnBhc3Nwb3J0PSZ2ZXJzaW9uPTIwMTAuNi4zLjYuMiZjcmFzaHR5cGU9MQ==&verify=068db92448c991d3ade2b957d10041f1)");
		// 使用系统提供的默认的恢复策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		try {
			// 执行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				logger.error("Method failed: "+ getMethod.getStatusLine());
			}
			
			// 读取内容
			Header[] headers = getMethod.getResponseHeaders("Location");
			if(CommonUtil.isNotEmpty(headers)){
			    // 从http header中获取目标地址
				result = headers[0].getValue();
			}
		} 
		catch (HttpException e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			logger.error("Please check your provided http address!", e);
		} 
		catch (Exception e) {
			// 发生网络异常
			logger.error(e);
		}
		finally {
			// 释放连接
			getMethod.releaseConnection();
		}
		return result;
	}
	
	//获取商口品的目标地址
	public static Source getStreamByUrl(String url){
		Source result = null;
		// 构造HttpClient的实例
		HttpClient httpClient = new HttpClient();
		// 创建GET方法的实例
		GetMethod getMethod = new GetMethod(url);
		// 使用系统提供的默认的恢复策略
		getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
		try {
			// 执行getMethod
			int statusCode = httpClient.executeMethod(getMethod);
			if (statusCode != HttpStatus.SC_OK) {
				logger.error("Method failed: "+ getMethod.getStatusLine());
			}
			result = new Source(getMethod.getResponseBodyAsStream());
			
		} 
		catch (HttpException e) {
			// 发生致命的异常，可能是协议不对或者返回的内容有问题
			logger.error("Please check your provided http address!", e);
		} 
		catch (Exception e) {
			// 发生网络异常
			logger.error(e);
		}
		finally {
			// 释放连接
			getMethod.releaseConnection();
		}
		return result;
	}
	
	public static String getTargetUrlByGet(String url, String referer){
		String result = "";
		// 构造HttpClient的实例
		org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
		HttpParams params = httpClient.getParams();   
		params.setParameter(ClientPNames.HANDLE_REDIRECTS, false);  
		HttpGet httpget = new HttpGet(url);
		httpget.setParams(params);
		httpget.addHeader("Referer", referer);
        try {
			HttpResponse response = httpClient.execute(httpget);
			org.apache.http.Header[] headers = response.getHeaders("Location");
			if (null != headers && headers.length > 0){
			   result = headers[0].getValue();
			}
		} 
        catch (ClientProtocolException e) {
			logger.error(e);
		}
        catch (IOException e) {
			logger.error(e);
		}
        return result;
	}
	
	public static void main(String[] args) throws IOException{
	}
	
	
	
}

